import * as Koa from 'koa';
import md5 = require('md5');
import { Transaction } from 'tiny-entity2';
import { Guid, route, RouteOptionsVerify, ServiceManager, UsingLock } from "../../common";
import { ApiDataContext } from '../../domain/apiDataContext';
import { AccountRoles } from '../../domain/models/accountRoles';
import { AccountRolesService } from '../../service/accountRolesService';
const accRoleServiceSvr = ServiceManager.Current.GetService<AccountRolesService>('AccountRolesService');

class AccountRolesController {
    @route(new RouteOptionsVerify('GET', '/api/accountroles'))
    async queryAccountRoles(ctx: Koa.Context, next) {
        let params = ctx.query;
        let data = await accRoleServiceSvr.QueryAccountRoles(params);
        ctx.response.body = data;
        await next();
    }
    @route(new RouteOptionsVerify('GET', '/api/accountroles/:id'))
    async getAccountRolesById(ctx: Koa.Context, next) {
        let id = ctx.params.id;
        let data = await accRoleServiceSvr.GetAccountRolesById(id);
        ctx.response.body = data;
        await next();
    }
    @route(new RouteOptionsVerify('POST', '/api/accountroles'))
    async createAccountRoles(ctx: Koa.Context, next) {
        let accroles: AccountRoles[] = ctx.request.body;
        let result: AccountRoles = new AccountRoles();
        if (accroles && accroles.length > 0) {
            await Transaction(new ApiDataContext(), async datactx => {
                await accRoleServiceSvr.DeleteAccountRoles(<AccountRoles>{ roleId: accroles[0].roleId }, datactx);

                for (let i = 0; i < accroles.length; i++) {
                    accroles[i].id = Guid.GetGuid();
                    result = await accRoleServiceSvr.CreateAccountRoles(accroles[i], datactx);
                }
            });

            ctx.response.body = result;
        }
        await next();
    }

    @route(new RouteOptionsVerify('DELETE', '/api/accountroles/:id'))
    async deleteAccountRoles(ctx: Koa.Context, next) {
        const id = ctx.params.id;
        let entity = new AccountRoles();
        entity.id = id;
        await UsingLock(entity.id, async () => {
            await accRoleServiceSvr.DeleteAccountRoles(entity);
        });

        ctx.response.body = {};
        await next();
    }
}